package org.inspursc.s0517.health.common.security;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.inspursc.s0517.health.common.vo.ResponseVO;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Service
@Slf4j
public class MyAuthenticationProcessingFilterEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        boolean isAjax = isAjaxRequest(request);
        log.info("MyAuthenticationProcessingFilterEntryPoint 是否是ajax请求：" + isAjax);
        if (isAjax) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/plain");
            ResponseVO responseVO = new ResponseVO();
            responseVO.setMessage("没有该权限或没有登录，请联系管理员！");
            responseVO.setCode(HttpStatus.UNAUTHORIZED.value());
            response.getWriter().write(JSONObject.toJSONString(responseVO));
            response.getWriter().close();
        }
    }

    public boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return header != null && "XMLHttpRequest".equals(header);
    }
}
